package com.haidong.web;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * doget和dopost代码有较大冗余,所以采用同一编程的方法
 * 由于请求参数在get请求的请求行中,但是在post却在请求体中
 * 实际上request中已经集成了获取请求参数的方法,存放在map中,get和post通用
 */
@WebServlet("/req2")
public class RequestDemo2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getMethod();
        //获取所有的请求参数集合,get和post通用方法
        Map<String,String[]> map = req.getParameterMap();
        //输出参数信息
        for (String key : map.keySet()) {
            System.out.print(key + ":");
            String[] values = map.get(key);
            for (String value : values) {
                System.out.println(value + " ");
            }
            System.out.println();
        }
        //获取某一个键的值(数组)
        String[] hobbies = req.getParameterValues("hobby");
        System.out.println("----------------");
        for (String hobby : hobbies) {
            System.out.println(hobby);
        }
        //获取某键的值(单个)
        String username = req.getParameter("username");
        String password = req.getParameter("password");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
